package com.security.system.controller;

import com.security.config.mobile.MobileCode;
import com.security.config.mobile.SmsSend;
import com.security.system.dao.SysUserDao;
import com.security.system.entity.SysUser;
import com.security.utils.R;
import com.security.utils.CaptchaUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.Map;

@Slf4j
@Controller
@RequestMapping("mobile")
public class MobileController {

    @Resource
    SysUserDao dao;

    @Resource
    SmsSend smsCodeSender;

    @GetMapping("")
    public String getMobileLoginHtml(){
        return "system/login/mobileLogin";
    }

    //获取 并 发送 手机验证码
    @PostMapping("getMobileCapcha")
    @ResponseBody
    public R getMobileCapcha(@RequestBody Map<String,Object> param, HttpSession session){
        SysUser user =  dao.findSysUserByMobile(param.get("mobile").toString());
        if(ObjectUtils.isEmpty(user)){
            return R.error(401,"您输入的手机号未曾注册");
        }
        MobileCode smsCode = new MobileCode(CaptchaUtils.MOBILE_Captcha().getCode(),user.getMobile(),60);
        if (smsCodeSender.sendSms(user.getMobile(),smsCode.getCode())){
            log.info("短信已发出"+smsCode.getCode());
            session.setAttribute(CaptchaUtils.CAPTCHA_MOBILE_KEY,smsCode);
            return R.success("ok",smsCode.getCode());
        }else {
            log.info("短信发送失败"+smsCode.getCode());
            return R.error(401,"验证码发送失败，请联系管理员");
        }
    }

}
